const express=require('express')
const app=express()
const cors=require('cors')
const expressJWT=require('express-jwt')
const config=require('./config')
const userInfoRouter=require('./router/userInfo')
const articleRouter=require('./router/article')
const getAllArticleRouter=require('./router/getAllArticle')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:false}))

app.use((req,res,next)=>{
    req.resSend=function(status,err){
        res.send({
            status,
            msg:err instanceof Error ? err.message:err
        })
    }
    next()
})

app.use(expressJWT({secret:config.secretKey,algorithms:['HS256']}).unless({path:[/^\/api/]}))

app.use('/api',userInfoRouter)
app.use(articleRouter)
app.use('/api',getAllArticleRouter)

app.use((err,req,res,next)=>{
    if(err.name==='UnauthorizedError'){
        return req.resSend(401,'身份认证失败！')
    }
    req.resSend(401,err)
    next()
})

app.listen(8080,()=>{
    console.log('server running at http://127.0.0.1:8080')
})